package com.example.common.event

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

/**
 * 自定义ShareFlowBus(在Kotlin开发中推荐使用)
 */
object ShareFlowBus {

    private val _shareFlow = MutableSharedFlow<CustomEvent>(extraBufferCapacity = 64)
    var shareFlow: SharedFlow<CustomEvent> = _shareFlow.asSharedFlow()

    suspend fun sendEvent(event: CustomEvent){
        _shareFlow.emit(event)
    }

    fun postAsync(event: CustomEvent) {
        CoroutineScope(Dispatchers.Default).launch {
            _shareFlow.emit(event)
        }
    }

    fun removeSubscribe(){
        _shareFlow.resetReplayCache()
    }

    // 订阅特定类型事件
    inline fun <reified T> subscribe(scope: CoroutineScope, crossinline onEvent: (T) -> Unit) =  shareFlow.filterIsInstance<T>().onEach { onEvent(it) }.launchIn(scope)

}